package cn.fetosoft.woodpecker.core.jmeter.element.assertion;

import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.entity.element.assertion.ResponseAssertionElement;
import cn.fetosoft.woodpecker.core.jmeter.element.AbstractElementBuild;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.assertions.ResponseAssertion;
import org.apache.jmeter.testelement.TestElement;
import org.springframework.stereotype.Component;

/**
 * 创建响应断言
 * @author guobingbing
 * @wechat t_gbinb
 * @since 2021/8/15 19:37
 */
@Component("responseAssertionImpl")
public class CreateResponseAssertionImpl extends AbstractElementBuild {

    private static final String TEST_FIELD = "Assertion.test_field";
    private static final int MATCH = 1;
    private static final int CONTAINS = 1 << 1;
    private static final int EQUALS = 1 << 3;
    private static final int SUBSTRING = 1 << 4;
    private static final int NOT = 1 << 2;
    private static final int OR = 1 << 5;

    @Override
    protected TestElement convert(BaseElement be) throws Exception {
        ResponseAssertionElement element = (ResponseAssertionElement) be;
        ResponseAssertion assertion = new ResponseAssertion();
        if(SCOPE_ALL.equals(element.getScope())){
            assertion.setScopeAll();
        }else if(SCOPE_PARENT.equals(element.getScope())){
            assertion.setScopeParent();
        }else if(SCOPE_CHILDREN.equals(element.getScope())){
            assertion.setScopeChildren();
        }else if(SCOPE_VARIABLE.equals(element.getScope())){
            assertion.setScopeVariable(element.getScopeVariable());
        }
        assertion.setProperty(TEST_FIELD, element.getTestField());
        if(StringUtils.isNotBlank(element.getAssumeSuccess())){
            assertion.setAssumeSuccess(Boolean.parseBoolean(element.getAssumeSuccess()));
        }else{
            assertion.setAssumeSuccess(false);
        }
        int testRule = Integer.parseInt(element.getTestRule());
        switch (testRule){
            case MATCH:
                assertion.setToMatchType();
                break;
            case CONTAINS:
                assertion.setToContainsType();
                break;
            case EQUALS:
                assertion.setToEqualsType();
                break;
            default:
                assertion.setToSubstringType();
                break;
        }
        if(StringUtils.isNotBlank(element.getTestNo())){
            assertion.setToNotType();
        }
        if(StringUtils.isNotBlank(element.getTestOr())){
            assertion.setToOrType();
        }
        if(StringUtils.isNotBlank(element.getTestStrings())){
            String[] testArr = element.getTestStrings().split(";");
            for(String str : testArr){
                assertion.addTestString(str);
            }
        }
        assertion.setCustomFailureMessage(element.getCustomMessage());
        return assertion;
    }
}
